package io.renren.wechat.support;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;

/**
 * @author dmcp@qq.com
 * @since 2021/11/21 22:06
 */
public abstract class ResponseEntityUtils {
    private static final Logger LOGGER = LoggerFactory.getLogger(ResponseEntityUtils.class);


    public static <T> boolean isSuccess(ResponseEntity<T> responseEntity) {
        final HttpHeaders headers = responseEntity.getHeaders();
        if (headers.containsKey("Error-Code")) {
            if (StringUtils.equals(headers.getFirst("Error-Code"), "0"))
                return true;
            else {
                LOGGER.warn("invoke qywx api failed, errmsg: {}", headers.getFirst("Error-Msg"));
                return false;
            }
        }

        return true;
    }

    public static <T> boolean isError(ResponseEntity<T> responseEntity) {
        final HttpHeaders headers = responseEntity.getHeaders();
        return headers.containsKey("Error-Code") && !StringUtils.equals(headers.getFirst("Error-Code"), "0");
    }

    public static <T> String getErrorCode(ResponseEntity<T> responseEntity) {
        final HttpHeaders headers = responseEntity.getHeaders();
        if (headers.containsKey("Error-Code")) {
            return headers.getFirst("Error-Code");
        }

        return null;
    }

    public static <T> String getErrorMsg(ResponseEntity<T> responseEntity) {
        final HttpHeaders headers = responseEntity.getHeaders();
        if (headers.containsKey("Error-Msg")) {
            return headers.getFirst("Error-Msg");
        }

        return null;
    }
}
